'use strict';

angular.module('com.dcos.app').controller('WorkFlowCopyController', function($window,$rootScope,$scope,$state,$stateParams, $filter, api, $uibModal, WorkFlowCreateService,TemplateService,TemplateDetailService) {
  
  var vm = this;
  
  vm.breadCrumbArr = [api.breadCrumbMap.workflow.root,api.breadCrumbMap.workflow.create.root];

  $scope.propertydata=[];

  $scope.formdata = {};

  $scope.curProjectId=$window.sessionStorage.getItem("curProjectId");

  vm.userid=$window.sessionStorage.getItem("curUserId");

  // if(!vm.userid)
  //   $state.go('login');

  vm.saving=false;
  
  $scope.pipeline=true;

  vm.menudata=[];

  $scope.curNodeId="";

  $scope.flowdata={};

  vm.t_id=$stateParams.t_id;

  vm.p_id='';
    
  vm.template={
    "p_id":vm.p_id,
    "t_name":"",
    "project_id":vm.curProjectId,
    "description":"",
    "status":"1",
    "create_user":vm.userid
  };

  function fnInitByTemplate() {
    TemplateDetailService.init(vm.t_id).then(function (response) {
      vm.menudata=response.data.menudata;
      angular.forEach(vm.menudata,function(item,index){
        angular.forEach(item.plugin,function(_item,_index){
          $scope.propertydata.push(_item);
        });
      });
      $scope.flowdata=response.data.flowdata;
      $scope.fnInitData();
    });
  }

  fnInitByTemplate();

  $scope.fnSave = function (data) {
    if(data.p_name){
        $rootScope.loading = true;
        WorkFlowCreateService.save(data).then(function (response) {
          $rootScope.loading = false;
          $state.go('app.workflow', {}, { reload: true });
          data.p_id=response.data.data.p_id;
          data.p_name=response.data.data.p_name;
          vm.p_id=data.p_id;
          vm.template.p_id=vm.p_id;
          vm.template.project_id=$scope.curProjectId;
      });
    }else{
        var modalInstance = $uibModal.open({
          animation: true,
          templateUrl: 'controllers/workflow/create/alert/alert.html',
          controller: 'AlertController as vm',
          resolve: {
          }
        });
    }

  }
  $scope.fnCreateTemplate = function () {
    var modalInstance = $uibModal.open({
      animation: true,
      templateUrl: 'controllers/workflow/create/template/create.html',
      controller: 'TemplateNameController as vm',
      resolve: {
        save:function(){return vm.fnSaveTemplate;},
        savedata:function(){return vm.template;}
      }
    });
  }
  vm.fnSaveTemplate = function (data) {
    $rootScope.loading = true;
    TemplateService.saveByPipeLine(data).then(function (response) {
      $rootScope.loading = false;
      $state.go('app.workflow', {}, { reload: true });
    });
  }
  $scope.fnRun = function () {
    $state.go('app.workflow.build', {'p_id':vm.p_id});
  }
});

